package com.robert.cool.weather.mvp.presenter;

import android.app.Activity;
import android.app.Application;
import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.OnLifecycleEvent;
import android.content.Intent;
import android.view.View;
import android.widget.ArrayAdapter;

import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;

import javax.inject.Inject;

import com.jess.arms.utils.RxLifecycleUtils;
import com.robert.cool.weather.mvp.contract.ChooseAreaContract;
import com.robert.cool.weather.mvp.model.api.Api;
import com.robert.cool.weather.mvp.model.entity.C;
import com.robert.cool.weather.mvp.model.entity.Location;
import com.robert.cool.weather.mvp.model.entity.User;
import com.robert.cool.weather.mvp.model.entity.db.City;
import com.robert.cool.weather.mvp.model.entity.db.County;
import com.robert.cool.weather.mvp.model.entity.db.Province;
import com.robert.cool.weather.mvp.ui.activity.MainActivity;
import com.robert.cool.weather.mvp.ui.activity.WeatherActivity;

import org.litepal.LitePal;
import org.litepal.crud.DataSupport;

import java.util.List;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 04/22/2020 23:10
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@FragmentScope
public class ChooseAreaPresenter extends BasePresenter<ChooseAreaContract.Model, ChooseAreaContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    @Inject
    ArrayAdapter<String> adapter;
    @Inject
    List<String> dataList;

    private List<Province> provinceList;
    private List<City> cityList;
    private List<County> countyList;
    private Province selectedProvince;
    private City selectedCity;
    private int currentLevel;
    private static final int LEVEL_PROVINCE = 0;
    private static final int LEVEL_CITY = 1;
    private static final int LEVEL_COUNTY = 2;

    @Inject
    public ChooseAreaPresenter(ChooseAreaContract.Model model, ChooseAreaContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    void onCreate() {
        mRootView.changeTitle("中国", View.GONE);
        queryProvinces();
    }



    /**
     * 请求城市数据
     * @param url
     * @param type
     */
    private void queryFromServer(String url, String type) {
        mModel.queryLocation(url)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(3, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();//显示下拉刷新的进度条
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    mRootView.hideLoading();//隐藏下拉刷新的进度条
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<List<Location>>(mErrorHandler) {
                    @Override
                    public void onNext(List<Location> locations) {
                        if ("province".equals(type)) {
                            saveProvince(locations);
                            queryProvinces();
                        } else if ("city".equals(type)) {
                            saveCities(locations);
                            queryCities();
                        } else if ("county".equals(type)) {
                            saveCounties(locations);
                            queryCounties();
                        }
                    }
                });
    }

    /**
     * 存储 县城
     * @param locations
     */
    private void saveCounties(List<Location> locations) {
        for (int i = 0; i < locations.size(); i++) {
            County county = new County();
            county.setCityId(selectedCity.getId());
            county.setCountyName(locations.get(i).getName());
            county.setWeatherId(locations.get(i).getWeather_id());
            county.save();
        }
    }

    /**
     * 存储 城市
     * @param locations
     */
    private void saveCities(List<Location> locations) {
        for (int i = 0; i < locations.size(); i++) {
            City city = new City();
            city.setCityName(locations.get(i).getName());
            city.setCityCode(locations.get(i).getId());
            city.setProvinceId(selectedProvince.getId());
            city.save();
        }
    }

    /**
     * 存储 省
     * @param locations
     */
    private void saveProvince(List<Location> locations) {
        for (int i = 0; i < locations.size(); i++) {
            Province province = new Province();
            province.setProvinceName(locations.get(i).getName());
            province.setProvinceCode(locations.get(i).getId());
            province.save();
        }
    }

    /**
     * 查询 省
     */
    public void queryProvinces() {
        provinceList = DataSupport.findAll(Province.class);
        if (provinceList.size() > 0) {
            dataList.clear();
            for (Province province : provinceList) {
                dataList.add(province.getProvinceName());
            }
            adapter.notifyDataSetChanged();
            mRootView.selectItem(0);
            currentLevel = LEVEL_PROVINCE;
        } else {
            queryFromServer(Api.QueryProvince, "province");
        }
    }

    /**
     * 查询 城市
     */
    private void queryCities() {
        cityList = DataSupport.where("provinceid = ?", String.valueOf(selectedProvince.getId())).find(City.class);
        if (cityList.size() > 0) {
            dataList.clear();
            for (City city : cityList) {
                dataList.add(city.getCityName());
            }
            adapter.notifyDataSetChanged();
            mRootView.selectItem(0);
            currentLevel = LEVEL_CITY;
        } else {
            int provinceCode = selectedProvince.getProvinceCode();
            queryFromServer(Api.QueryProvince + "/" + provinceCode, "city");
        }
    }

    /**
     * 查询 县城
     */
    private void queryCounties() {
        countyList = DataSupport.where("cityid = ?", String.valueOf(selectedCity.getId())).find(County.class);
        if (countyList.size() > 0) {
            dataList.clear();
            for (County county : countyList) {
                dataList.add(county.getCountyName());
            }
            adapter.notifyDataSetChanged();
            mRootView.selectItem(0);
            currentLevel = LEVEL_COUNTY;
        } else {
            int provinceCode = selectedProvince.getProvinceCode();
            int cityCode = selectedCity.getCityCode();
            queryFromServer(Api.QueryProvince + "/" + provinceCode + "/" + cityCode, "county");
        }
    }

    /**
     * 点击列表查询下级
     * @param i
     */
    public void clickItem(int i) {
        if (currentLevel == LEVEL_PROVINCE) {
            selectedProvince = provinceList.get(i);
            mRootView.changeTitle(selectedProvince.getProvinceName(), View.VISIBLE);
            queryCities();
        } else if (currentLevel == LEVEL_CITY) {
            selectedCity = cityList.get(i);
            mRootView.changeTitle(selectedCity.getCityName(), View.VISIBLE);
            queryCounties();
        }else if (currentLevel == LEVEL_COUNTY){
            String weatherId = countyList.get(i).getWeatherId();
            Activity topActivity = mAppManager.getTopActivity();
            if (topActivity instanceof MainActivity) {
                Intent intent = new Intent(mApplication, WeatherActivity.class);
                intent.putExtra(C.WeatherId, weatherId);
                mAppManager.startActivity(intent);
                mRootView.killMyself();
            }else if (topActivity instanceof WeatherActivity){
                WeatherActivity weatherActivity = (WeatherActivity) topActivity;
                weatherActivity.changeCity(weatherId);
            }
        }
    }

    /**
     * 下级列表返回上级
     */
    public void onBackButtonClick() {
        if (currentLevel == LEVEL_COUNTY) {
            mRootView.changeTitle(selectedProvince.getProvinceName(), View.VISIBLE);
            queryCities();
        } else if (currentLevel == LEVEL_CITY) {
            mRootView.changeTitle("中国", View.GONE);
            queryProvinces();
        }
    }
}
